<template>
  <div class="freight-rule">
    <el-card>
      <div class="table-actions">
        <el-button type="primary" @click="openDialog('add')">新增</el-button>
        <!-- <el-button type="success" @click="importDialogVisible = true">批量导入</el-button> -->
      </div>
      <el-table :data="pagedList" style="width: 100%">
        <el-table-column prop="logisticsName" label="名称" width="150">
          <template #default="scope">
            <div style="display: flex; align-items: center; gap: 8px;">
              <el-avatar v-if="scope.row.logoUrl" :src="scope.row.logoUrl" :size="32" shape="square" />
              <el-avatar v-else :size="32" shape="square" style="background-color: #f5f7fa; color: #909399;">
                <el-icon><Box /></el-icon>
              </el-avatar>
              <span>{{ scope.row.logisticsName }}</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="logisticsType" label="类型" width="100" />
        <el-table-column prop="calcMode" label="计费模式" width="120">
          <template #default="scope">
            {{ calcModeLabel(scope.row.calcMode) }}
          </template>
        </el-table-column>
        <el-table-column prop="speed" label="物流速度" width="100">
          <template #default="scope">
            <span>{{ scope.row.speed }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="features" label="物流特点" width="200">
          <template #default="scope">
            <div style="max-width: 180px; word-wrap: break-word; line-height: 1.4;">
              {{ scope.row.features }}
            </div>
          </template>
        </el-table-column>
        
        <!-- <el-table-column prop="weightLimit" label="重量限制(G)" width="120" /> -->
        <el-table-column prop="taxCode" label="税号" width="100" />
        <el-table-column prop="remark" label="备注" min-width="120" />
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="scope">
            <el-button size="small" @click="viewDetail(scope.row.id)" type="primary" plain>详情</el-button>
            <el-button v-if="scope.row.logisticsName === 'EMS'" size="small" @click="viewEMSDetail" type="success" plain>EMS详情</el-button>
            <el-button size="small" @click="openDialog('edit', scope.row, scope.$index)">编辑</el-button>
            <el-button size="small" type="danger" @click="deleteRule(scope.$index)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        v-model:current-page="page.current"
        v-model:page-size="page.size"
        :total="list.length"
        layout="total, sizes, prev, pager, next, jumper"
        :page-sizes="[10, 20, 50]"
        style="margin-top: 12px; text-align: right;"
      />
      <el-dialog v-model="dialog.visible" :title="dialog.mode === 'add' ? '新增运费规则' : '编辑运费规则'" width="700px" :close-on-click-modal="false">
        <el-form :model="dialog.form" label-width="120px">
          <el-form-item label="物流名称">
            <el-input v-model="dialog.form.logisticsName" placeholder="请输入物流名称" />
          </el-form-item>
          <el-form-item label="物流Logo">
            <el-upload
              class="logo-uploader"
              action=""
              :show-file-list="false"
              :on-success="handleLogoSuccess"
              :before-upload="beforeLogoUpload"
              :auto-upload="false"
              :on-change="handleLogoChange"
            >
              <img v-if="dialog.form.logoUrl" :src="dialog.form.logoUrl" class="logo" />
              <el-icon v-else class="logo-uploader-icon"><Plus /></el-icon>
            </el-upload>
            <div class="upload-tip">建议尺寸：100x100px，支持jpg、png格式</div>
          </el-form-item>
          <el-form-item label="物流方式">
            <el-select v-model="dialog.form.logisticsType" style="width: 200px">
              <el-option label="直通" value="直通" />
              <el-option label="直邮" value="直邮" />
              <el-option label="日本国内" value="日本国内" />
              <el-option label="中国国内" value="中国国内" />
            </el-select>
          </el-form-item>
          <el-form-item label="物流速度">
            <div style="display: flex; align-items: center; gap: 8px;">
              <el-input-number
                v-model="dialog.form.speedMin"
                :min="1"
                :max="365"
                placeholder="最少天数"
                style="width: 120px"
              />
              <span>~</span>
              <el-input-number
                v-model="dialog.form.speedMax"
                :min="1"
                :max="365"
                placeholder="最多天数"
                style="width: 120px"
              />
              <span>日</span>
            </div>
          </el-form-item>
          <el-form-item label="物流特点">
            <el-input
              v-model="dialog.form.features"
              type="textarea"
              :rows="3"
              placeholder="请输入物流特点描述"
              style="width: 100%"
            />
          </el-form-item>
          <el-form-item label="价格计算模式">
            <el-select v-model="dialog.form.calcMode" style="width: 200px">
              <el-option label="不计算" value="none" />
              <el-option label="首重+续重" value="first_additional" />
              <el-option label="续重" value="additional" />
              <el-option label="详表" value="table" />
            </el-select>
          </el-form-item>
          <el-form-item label="重量限制(G)">
            <el-input-number v-model="dialog.form.weightLimit" :min="0" />
          </el-form-item>
          <template v-if="dialog.form.calcMode === 'none'">
            <el-form-item label="税号">
              <el-input v-model="dialog.form.taxCode" />
            </el-form-item>
            <el-form-item label="备注">
              <el-input v-model="dialog.form.remark" />
            </el-form-item>
          </template>
          <template v-else-if="dialog.form.calcMode === 'first_additional'">
            <el-form-item label="首重(G)">
              <el-input-number v-model="dialog.form.firstWeight" :min="0" />
            </el-form-item>
            <el-form-item label="首重价格">
              <el-input-number v-model="dialog.form.firstPrice" :min="0" />
            </el-form-item>
            <el-form-item label="首重价格（备选）">
              <el-input-number v-model="dialog.form.firstPriceAlt" :min="0" />
            </el-form-item>
            <el-form-item label="续重(G)">
              <el-input-number v-model="dialog.form.additionalWeight" :min="0" />
            </el-form-item>
            <el-form-item label="续重价格">
              <el-input-number v-model="dialog.form.additionalPrice" :min="0" />
            </el-form-item>
            <el-form-item label="续重价格（备选）">
              <el-input-number v-model="dialog.form.additionalPriceAlt" :min="0" />
            </el-form-item>
            <el-form-item label="税号">
              <el-input v-model="dialog.form.taxCode" />
            </el-form-item>
            <el-form-item label="备注">
              <el-input v-model="dialog.form.remark" />
            </el-form-item>
          </template>
          <template v-else-if="dialog.form.calcMode === 'additional'">
            <el-form-item label="续重(G)">
              <el-input-number v-model="dialog.form.onlyAdditionalWeight" :min="0" />
            </el-form-item>
            <el-form-item label="续重价格">
              <el-input-number v-model="dialog.form.onlyAdditionalPrice" :min="0" />
            </el-form-item>
            <el-form-item label="续重价格（备选）">
              <el-input-number v-model="dialog.form.onlyAdditionalPriceAlt" :min="0" />
            </el-form-item>
            <el-form-item label="税号">
              <el-input v-model="dialog.form.taxCode" />
            </el-form-item>
            <el-form-item label="备注">
              <el-input v-model="dialog.form.remark" />
            </el-form-item>
          </template>
          <template v-else-if="dialog.form.calcMode === 'table'">
            <el-form-item label="税号">
              <el-input v-model="dialog.form.taxCode" />
            </el-form-item>
            <el-form-item label="备注">
              <el-input v-model="dialog.form.remark" />
            </el-form-item>
            <el-form-item label="详表">
              <div style="width:100%">
                <el-table :data="dialog.form.tableDetail" style="width:100%;margin-bottom:8px;">
                  <el-table-column prop="weight" label="重量(G)" width="120">
                    <template #default="scope">
                      <el-input-number v-model="scope.row.weight" :min="0" style="width: 140px" controls-position="right" />
                    </template>
                  </el-table-column>
                  <el-table-column prop="price" label="价格" width="120">
                    <template #default="scope">
                      <el-input-number v-model="scope.row.price" :min="0" style="width: 140px" controls-position="right" />
                    </template>
                  </el-table-column>
                  <el-table-column label="操作" width="80">
                    <template #default="scope">
                      <el-button size="small" type="danger" @click="removeTableRow(scope.$index)">删除</el-button>
                    </template>
                  </el-table-column>
                </el-table>
                <el-button size="small" @click="addTableRow">添加一行</el-button>
              </div>
            </el-form-item>
          </template>
        </el-form>
        <template #footer>
          <el-button @click="dialog.visible = false">取消</el-button>
          <el-button type="primary" @click="saveRule">保存</el-button>
        </template>
      </el-dialog>
      <el-dialog v-model="importDialogVisible" title="批量导入运费规则" width="400px" :close-on-click-modal="false">
        <div style="margin-bottom: 12px;">
          <el-button type="primary" @click="downloadTemplate">下载模板</el-button>
        </div>
        <el-upload
          class="upload-demo"
          drag
          action=""
          :auto-upload="false"
          :show-file-list="true"
          :on-change="handleFileChange"
          accept=".xlsx,.xls"
        >
          <i class="el-icon-upload"></i>
          <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        </el-upload>
        <template #footer>
          <el-button @click="importDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleImport">导入</el-button>
        </template>
      </el-dialog>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, Box } from '@element-plus/icons-vue'
import { useRouter, useRoute } from 'vue-router'
import * as XLSX from 'xlsx'
import type { FreightRuleV2, FreightCalcMode } from '@/types/freightRule'

const router = useRouter()
const route = useRoute()

const calcModeLabel = (mode: FreightCalcMode) => {
  switch (mode) {
    case 'none': return '不计算'
    case 'first_additional': return '首重+续重'
    case 'additional': return '续重'
    case 'table': return '详表'
    default: return ''
  }
}


// 从sessionStorage加载数据或使用默认数据
const loadListData = () => {
  const savedData = sessionStorage.getItem('freightRuleList')
  if (savedData) {
    try {
      return JSON.parse(savedData)
    } catch (e) {
      console.error('解析保存的数据失败:', e)
    }
  }
  return getDefaultListData()
}

// 保存数据到sessionStorage
const saveListData = () => {
  console.log('列表页 - 保存数据到sessionStorage:', list.value)
  sessionStorage.setItem('freightRuleList', JSON.stringify(list.value))
}

// 获取默认列表数据
const getDefaultListData = () => [
  {
    id: '1',
    logisticsName: 'EMS',
    logoUrl: 'https://via.placeholder.com/100x100/00A651/FFFFFF?text=EMS',
    logisticsType: '直邮',
    speed: '2~5日',
    features: '最快速，空运，有等级折扣，航空禁运品不可选',
    calcMode: 'table',
    weightLimit: 2000,
    taxCode: 'A123',
    remark: '追跡サービス・保険200万円まで'
  },
  {
    id: '2',
    logisticsName: '航空便',
    logoUrl: 'https://via.placeholder.com/100x100/1E88E5/FFFFFF?text=航空',
    logisticsType: '直通',
    speed: '7~20日',
    features: '快速，空运，航空禁运品不可选',
    calcMode: 'first_additional',
    weightLimit: 1000,
    taxCode: 'B456',
    firstWeight: 500,
    firstPrice: 205,
    firstPriceAlt: 200,
    additionalWeight: 100,
    additionalPrice: 20,
    additionalPriceAlt: 18,
    remark: ''
  },
  {
    id: '3',
    logisticsName: '可追踪小航空',
    logoUrl: 'https://via.placeholder.com/100x100/FF6B35/FFFFFF?text=小航空',
    logisticsType: '直邮',
    speed: '10~14日',
    features: '空运，适合8千元以下小包裹，航空禁运品不可选',
    calcMode: 'additional',
    weightLimit: 5000,
    taxCode: 'C789',
    onlyAdditionalWeight: 100,
    onlyAdditionalPrice: 12,
    onlyAdditionalPriceAlt: 10,
    remark: ''
  },
  {
    id: '4',
    logisticsName: '船运',
    logoUrl: 'https://via.placeholder.com/100x100/4B0082/FFFFFF?text=船运',
    logisticsType: '直通',
    speed: '30~60日',
    features: '海运，适合重物/不能空运的商品',
    calcMode: 'table',
    weightLimit: 10000,
    taxCode: 'D012',
    tableDetail: [ { weight: 500, price: 180 }, { weight: 1000, price: 200 }, { weight: 2000, price: 250 } ] as { weight: number; price: number }[],
    remark: ''
  },

]

const list = ref<FreightRuleV2[]>(loadListData())
const page = ref({ current: 1, size: 10 })
const pagedList = computed(() => {
  const start = (page.value.current - 1) * page.value.size
  return list.value.slice(start, start + page.value.size)
})
const dialog = ref({
  visible: false,
  mode: 'add' as 'add' | 'edit',
  form: {
    logisticsName: '',
    logoUrl: '',
    logisticsType: '直通' as '直通' | '直邮' | '日本国内' | '中国国内',
    speedMin: 0,
    speedMax: 0,
    features: '',
    calcMode: 'none' as FreightCalcMode,
    weightLimit: 0,
    taxCode: '',
    remark: '',
    firstWeight: 0, firstPrice: 0, firstPriceAlt: 0, additionalWeight: 0, additionalPrice: 0, additionalPriceAlt: 0,
    onlyAdditionalWeight: 0, onlyAdditionalPrice: 0, onlyAdditionalPriceAlt: 0,
    tableDetail: [] as { weight: number; price: number }[]
  },
  editIndex: -1
})
function openDialog(mode: 'add' | 'edit', row?: any, idx?: number) {
  dialog.value.mode = mode
  if (mode === 'add') {
    dialog.value.form = {
      logisticsName: '',
      logoUrl: '',
      logisticsType: '直通',
      speedMin: 0,
      speedMax: 0,
      features: '',
      calcMode: 'none',
      weightLimit: 0,
      taxCode: '',
      remark: '',
      firstWeight: 0, firstPrice: 0, firstPriceAlt: 0, additionalWeight: 0, additionalPrice: 0, additionalPriceAlt: 0,
      onlyAdditionalWeight: 0, onlyAdditionalPrice: 0, onlyAdditionalPriceAlt: 0,
      tableDetail: []
    }
    dialog.value.editIndex = -1
  } else if (row && typeof idx === 'number') {
    dialog.value.form = JSON.parse(JSON.stringify(row))
    // 确保新字段存在
    if (!dialog.value.form.logoUrl) dialog.value.form.logoUrl = ''
    if (!dialog.value.form.features) dialog.value.form.features = ''

    // 处理速度字段转换
    if (row.speed && typeof row.speed === 'string') {
      const speedMatch = row.speed.match(/(\d+)~(\d+)日/)
      if (speedMatch) {
        dialog.value.form.speedMin = parseInt(speedMatch[1])
        dialog.value.form.speedMax = parseInt(speedMatch[2])
      } else {
        dialog.value.form.speedMin = 0
        dialog.value.form.speedMax = 0
      }
    } else {
      dialog.value.form.speedMin = 0
      dialog.value.form.speedMax = 0
    }

    dialog.value.editIndex = idx
  }
  dialog.value.visible = true
}
function saveRule() {
  const idx = dialog.value.editIndex

  // 构建保存的数据
  const saveData: any = { ...dialog.value.form }

  // 将speedMin和speedMax转换为speed字段
  if (saveData.speedMin && saveData.speedMax) {
    saveData.speed = `${saveData.speedMin}~${saveData.speedMax}日`
  } else {
    saveData.speed = ''
  }

  // 删除临时字段
  delete saveData.speedMin
  delete saveData.speedMax

  if (dialog.value.mode === 'add') {
    const newRule = {
      ...saveData,
      id: Date.now().toString(),
      createTime: new Date().toLocaleString('zh-CN'),
      updateTime: new Date().toLocaleString('zh-CN'),
      creator: '当前用户',
      updater: '当前用户'
    }
    list.value.push(newRule)
  } else if (idx > -1) {
    const currentRule: any = list.value[idx]
    const updatedRule = {
      ...saveData,
      id: currentRule.id,
      createTime: currentRule.createTime || new Date().toLocaleString('zh-CN'),
      updateTime: new Date().toLocaleString('zh-CN'),
      creator: currentRule.creator || '系统',
      updater: '当前用户'
    }
    list.value[idx] = updatedRule
  }

  // 保存到sessionStorage
  saveListData()
  dialog.value.visible = false
}

// 查看详情
function viewDetail(id: string) {
  console.log('列表页 - 点击查看详情，ID:', id)
  console.log('列表页 - 当前list数据:', list.value)
  router.push(`/settings/freight-rule/${id}`)
}

// 查看EMS详情
function viewEMSDetail() {
  console.log('列表页 - 点击查看EMS详情')
  router.push('/settings/freight-rule/ems/detail')
}

// 删除规则
function deleteRule(index: number) {
  ElMessageBox.confirm('确定要删除这条物流规则吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    list.value.splice(index, 1)
    // 保存到sessionStorage
    saveListData()
    ElMessage.success('删除成功')
  }).catch(() => {
    // 用户取消删除
  })
}
function addTableRow() {
  dialog.value.form.tableDetail = dialog.value.form.tableDetail || []
  dialog.value.form.tableDetail.push({ weight: 0, price: 0 })
}
function removeTableRow(idx: number) {
  dialog.value.form.tableDetail.splice(idx, 1)
}

// Logo上传相关函数
function handleLogoSuccess(_response: any, file: any) {
  dialog.value.form.logoUrl = URL.createObjectURL(file.raw)
}

function beforeLogoUpload(file: any) {
  const isJPG = file.type === 'image/jpeg' || file.type === 'image/png'
  const isLt2M = file.size / 1024 / 1024 < 2

  if (!isJPG) {
    ElMessage.error('上传头像图片只能是 JPG/PNG 格式!')
  }
  if (!isLt2M) {
    ElMessage.error('上传头像图片大小不能超过 2MB!')
  }
  return isJPG && isLt2M
}

function handleLogoChange(file: any) {
  if (file.raw) {
    const reader = new FileReader()
    reader.onload = (e) => {
      dialog.value.form.logoUrl = e.target?.result as string
    }
    reader.readAsDataURL(file.raw)
  }
}
const importDialogVisible = ref(false)
function downloadTemplate() {
  // 按mock结构生成模板
  const wsData = [
    [
      '物流名称',
      '物流Logo(URL)',
      '物流方式',
      '物流速度',
      '物流特点(用逗号分隔)',
      '价格计算模式',
      '重量限制(G)',
      '税号',
      '备注',
      '首重(G)',
      '首重价格',
      '首重价格（备选）',
      '续重(G)',
      '续重价格',
      '续重价格（备选）',
      '详表（重量1）',
      '详表（价格1）',
      '详表（重量2）',
      '详表（价格2）'
    ],
    [
      '顺丰国际',
      'https://via.placeholder.com/100x100/FF6B35/FFFFFF?text=SF',
      '直通',
      '极速',
      '包税,可追踪,时效保证',
      'none/first_additional/additional/table',
      2000,
      'A123',
      '无需计算',
      1000,
      50,
      45,
      500,
      20,
      18,
      1000,
      10,
      2000,
      18
    ]
  ]
  const ws = XLSX.utils.aoa_to_sheet(wsData)
  const wb = XLSX.utils.book_new()
  XLSX.utils.book_append_sheet(wb, ws, '模板')
  XLSX.writeFile(wb, '国际物流规则导入模板.xlsx')
}
function handleFileChange(_file: any) {
  // TODO: 处理文件选择
}
function handleImport() {
  // TODO: 解析Excel并导入数据
  ElMessage.success('导入成功')
  importDialogVisible.value = false
}

// 页面初始化
onMounted(() => {
  // 确保数据已保存到sessionStorage
  saveListData()

  // 检查是否有编辑参数
  const editId = route.query.edit as string
  if (editId) {
    const index = list.value.findIndex(item => item.id === editId)
    if (index > -1) {
      openDialog('edit', list.value[index], index)
    }
  }
})
</script>

<style scoped>
.freight-rule {
  padding: 16px;
}
.table-actions {
  margin-bottom: 12px;
  display: flex;
  align-items: center;
}

/* Logo上传样式 */
.logo-uploader {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  width: 100px;
  height: 100px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.logo-uploader:hover {
  border-color: #409eff;
}

.logo-uploader-icon {
  font-size: 28px;
  color: #8c939d;
}

.logo {
  width: 100px;
  height: 100px;
  object-fit: cover;
  border-radius: 6px;
}

.upload-tip {
  font-size: 12px;
  color: #999;
  margin-top: 8px;
  line-height: 1.4;
}
</style>